//
//  Unity.m
//  PowerOnHD
//
//  Created by Srain on 13-5-29.
//  Copyright (c) 2013年 lu yingzhi. All rights reserved.
//

#import "Unity.h"
//#import "MainAppDelegate.h"
//#import "SUNAppDelegate.h"
#import "sys/utsname.h"
#import "SGSaveFile.h"
#import "UIDevice+IdentifierAddition.h"
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
@implementation Unity
+ (UIImageView *)rotate360DegreeWithImageView:(UIImageView *)imageView{
    CABasicAnimation *animation = [ CABasicAnimation
                                   animationWithKeyPath: @"transform" ];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    
    //围绕Z轴旋转，垂直与屏幕
    animation.toValue = [ NSValue valueWithCATransform3D:
                         
                         CATransform3DMakeRotation(M_PI, 0.0, 0.0, 1.0) ];
    animation.duration = 0.5;
    //旋转效果累计，先转180度，接着再旋转180度，从而实现360旋转
    animation.cumulative = YES;
    animation.repeatCount = 1000;
    
    //在图片边缘添加一个像素的透明区域，去图片锯齿
    CGRect imageRrect = CGRectMake(0, 0,imageView.frame.size.width, imageView.frame.size.height);
    UIGraphicsBeginImageContext(imageRrect.size);
    [imageView.image drawInRect:CGRectMake(1,1,imageView.frame.size.width-2,imageView.frame.size.height-2)];
    imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [imageView.layer addAnimation:animation forKey:nil];
    return imageView;
}

+ (void)saveCache:(NSString*)type  andString:(NSMutableArray *)str
{
    NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];
    NSString * key = [NSString stringWithFormat:@"%@",type];
    [setting setObject:str forKey:key];
    [setting synchronize];
}
+ (NSMutableArray *)getCache:(NSString *)type
{
    NSUserDefaults * settings = [NSUserDefaults standardUserDefaults];
    NSString *key = [NSString stringWithFormat:@"%@",type];
    
    NSMutableArray *value = [settings objectForKey:key];
    return value;
}

+(UIColor*)getBackColor
{
    return [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0];
}
+(UIColor*)getTableItemSeleteColor
{
    return [UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0];
}
+(NSDate *)stringToDate:(NSString *)string
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd"];
    NSDate *destDate= [dateFormatter dateFromString:string];
    return destDate;
}
+(NSDate *)stringToTime:(NSString *)string
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    NSDate *destDate= [dateFormatter dateFromString:string];
    return destDate;
}
+(NSDate *)stringToTimeMM:(NSString *)string
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm"];
    NSDate *destDate= [dateFormatter dateFromString:string];
    return destDate;
}
+(NSString *)dateToString:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *destDateString = [dateFormatter stringFromDate:date];
    return destDateString;
}
+(NSString *)timeToString:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *destDateString = [dateFormatter stringFromDate:date];
    return destDateString;
}
+(NSString *)timeToMMString:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *destDateString = [dateFormatter stringFromDate:date];
    return destDateString;
}

+(NSString *)timeToMMString
{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *destDateString = [dateFormatter stringFromDate:date];
    return destDateString;
}


+(CGFloat) getLabelHeightWithWidth:(CGFloat)labelWidth andDefaultHeight:(CGFloat)labelDefaultHeight andFontSize:(CGFloat)fontSize andText:(NSString *)text
{
	CGSize constraint = CGSizeMake(labelWidth, 20000.0f);
	
	CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
	
	CGFloat labelHeight = MAX(size.height, labelDefaultHeight);
	
	return labelHeight;
}
+(NSString*)systemTime
{
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
	[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
	[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.sss"];
	return [dateFormatter stringFromDate:[NSDate date]];
}
+(NSString*)systemTimeToMM
{
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
	[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
	[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
	return [dateFormatter stringFromDate:[NSDate date]];
}


//encodeURL只能用来对url中的component编码，不能用来对整个url进行编码。
//+(NSString*)encodeURL:(NSString*) unescapedString
//{
//  NSString* escapedUrlString= (NSString*) CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)unescapedString, NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]{}", kCFStringEncodingUTF8 );
//        
//    return unescapedString;
//}

- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];
    
    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}


+(UIColor *)getColor:(NSString *) stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    
    if ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

static BOOL memoryInfo(vm_statistics_data_t *vmStats)
{
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)vmStats, &infoCount);
    
    return kernReturn == KERN_SUCCESS;
}


+(void)logMemoryInfo
{
    vm_statistics_data_t vmStats;
    
    if (memoryInfo(&vmStats)) {
        NSLog(@"free: %lf M\nactive: %u\ninactive: %u\nwire: %u\nzero fill: %u\nreactivations: %u\npageins: %u\npageouts: %u\nfaults: %u\ncow_faults: %u\nlookups: %u\nhits: %u",
              (vmStats.free_count * vm_page_size/ 1024.0) / 1024.0,
              vmStats.active_count * vm_page_size,
              vmStats.inactive_count * vm_page_size,
              vmStats.wire_count * vm_page_size,
              vmStats.zero_fill_count * vm_page_size,
              vmStats.reactivations * vm_page_size,
              vmStats.pageins * vm_page_size,
              vmStats.pageouts * vm_page_size,
              vmStats.faults,
              vmStats.cow_faults,
              vmStats.lookups,
              vmStats.hits
              );
        
    }
}



+(BOOL)strToBool:(NSString*)str
{
    BOOL result = NO;
    if ([str intValue] == 0 || [str isEqualToString:@"false"]) {
        result = NO;
    }else if ([str intValue] == 1 || [str isEqualToString:@"true"]){
        result = YES;
    }
    return result;
}
+(UIViewController*)getViewController:(UIView*)view {
    
    for (UIView* next = [view superview]; next; next = next.superview) {
        
        UIResponder* nextResponder = [next nextResponder];
        
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            
            return (UIViewController*)nextResponder;
            
        }
        
    }
    
    return nil;
    
}
+(NSString*)intToString:(int)temp
{
    return [NSString stringWithFormat:@"%d",temp];
}

+(void)toViewController:(UINavigationController*)navigationController withLastCount:(int)count
{
    int nvcount = [navigationController.viewControllers count];
    if (count>=0 &&  nvcount >= count) {
        UIViewController* tempviewController = [navigationController.viewControllers objectAtIndex:([navigationController.viewControllers count]-count)];
        if (tempviewController!=nil) {
            [navigationController popToViewController:tempviewController animated:YES];
        }
    }
    
}

//+(void)removeSTPFromSuperview
//{
//	NSMutableArray *subviewsArr = [[NSMutableArray alloc ] initWithCapacity:3];
//	for (UIView *v in [[[UIApplication sharedApplication] keyWindow] subviews])
//	{
//		if ([v isKindOfClass:[STProgressView class]])
//		{
//			[subviewsArr addObject:v];
//		}
//	}
//	for (UIView *review in subviewsArr)
//	{
//		[review removeFromSuperview];
//	}
//	[subviewsArr release];
//}
//
//
//+(void)ShowWait:(NSString*)text
//{
//    //[Unity removeSTPFromSuperview];
//    UIWindow * keyWin = [[UIApplication sharedApplication] keyWindow];
//	if (keyWin != nil)
//	{
//        STProgressView* tempddd = [[STProgressView alloc]initWithFrame:CGRectMake(0, 0, KWindowWidth, iPhone5?568:480) withType:ESTPWaiting];
//        [keyWin addSubview:tempddd];
//        tempddd.tag = 2010;
//        [tempddd show:text];
//        [tempddd release];
//    }
//}
//
//+(void)HideWait
//{
//    UIWindow * keyWin = [[UIApplication sharedApplication] keyWindow];
//	if (keyWin != nil)
//	{
//        UIView *bgView=(UIView*)[keyWin viewWithTag:2010];
//        [bgView removeFromSuperview];
//	}
//}
//
//+(void)showAlert:(NSString*)message
//{
//    [Unity removeSTPFromSuperview];
//    UIWindow * keyWin = [[UIApplication sharedApplication] keyWindow];
//	if (keyWin != nil)
//	{
//        STProgressView* tempddd = [[STProgressView alloc]initWithFrame:CGRectMake(0, 0, KWindowWidth, iPhone5?568:480) withType:ESTPClew];
//        tempddd.tag = 2011;
//        [keyWin addSubview:tempddd];
//        [tempddd show:message];
//        [tempddd release];
//    }
//}
//
//+(void)showAlert:(NSString *)title withContent:(NSString*)content withLeftBtn:(NSString*)leftText withRightBtn:(NSString*)rightText withDelegate:(id<STDialogViewDelegate>)delegate
//{
//    UIWindow * keyWin = [[UIApplication sharedApplication] keyWindow];
//	if (keyWin != nil)
//	{
//        STDialogView* tempview = [[STDialogView alloc]initWithFrame:CGRectMake(0, 0, KWindowWidth, iPhone5?568:480) withTitle:title withContent:content withLeftBtn:leftText withRightBtn:rightText];
//        tempview.tag = 2012;
//        tempview.delegate = delegate;
//        [keyWin addSubview:tempview];
//        [tempview release];
//    }
//}

+ (BOOL)isBlankString:(NSString *)string
{
    
    if (string == nil) {
        
        return YES;
        
    }
    
    if (string == NULL) {
        
        return YES;
        
    }
    
    if ([string isKindOfClass:[NSNull class]]) {
        
        return YES;
        
    }
    
    if ([string isKindOfClass:[NSString class]]) {
        if ([string isEqualToString:@"(null)"]||[string isEqualToString:@"<null>"]) {
            return YES;
        }
        
        if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
            
            return YES;
            
        }
    }
    
    
    
    return NO;
    
}
//验证验证码
+(BOOL)isMsgCode:(NSString *)code{
    NSString *telRegex = @"[0-9]{4,6}";
    NSPredicate *telTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", telRegex];
    return [telTest evaluateWithObject:code];
}
//验证QQ
+(BOOL)isValidateQQ:(NSString *)QQ{
    NSString *telRegex = @"1[0-9]{10}";
    NSPredicate *telTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", telRegex];
    return [telTest evaluateWithObject:QQ];
}
//验证手机
+(BOOL)isValidateTelphone:(NSString *)telPhone{
    NSString *telRegex = @"1[0-9]{10}";
    NSPredicate *telTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", telRegex];
    return [telTest evaluateWithObject:telPhone];
}
//验证email
+(BOOL)verfierEmail:(NSString *)email
{
    BOOL result = YES;
    
    NSString* regex = @"(^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$)";
    
    NSPredicate* pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    result = [pred evaluateWithObject:email];
    
    return result;
}

//验证6-18位字母或数字的密码
+(BOOL)verfierPwd:(NSString*)password
{
    BOOL result = YES;
    
    if (password.length <6 || password.length >18) {
        result = NO;
    }
    
    return result;
}

+(SystemVersionType)currentVersion;
{
    double version = [[UIDevice currentDevice].systemVersion doubleValue];//判定系统版本。
    if (version>=5.0f && version<6.0f) {
        return ios5;
    }else
        if (version>=6.0f && version<7.0f) {
            return ios6;
        }else if (version >=7.0f){
            
            return ios7;
        }
    return noVersion;
}
+(NSString*)UUID
{
    NSString*temp=[SGSaveFile getObjectFromSystemWithKey:@"uuid"];
    if (self.UUID==nil) {
        temp=[[UIDevice currentDevice] uniqueDeviceIdentifier];
        [SGSaveFile saveObjectToSystem:temp forKey:@"uuid"];
    }
    return temp;
}

+(double)GetStringTimeDiff:(NSString*)timeS timeE:(NSString*)timeE
{
    double timeDiff = 0.0;
    NSDateFormatter *formatters = [[NSDateFormatter alloc] init];
    [formatters setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];
    NSDate *dateS = [formatters dateFromString:timeS];
    
    NSDateFormatter *formatterE = [[NSDateFormatter alloc] init];
    [formatterE setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];
    NSDate *dateE = [formatterE dateFromString:timeE];
    
    timeDiff = [dateE timeIntervalSinceDate:dateS ];
    return timeDiff;
}
+(NSString *)requestSomeApiData:(NSMutableDictionary *)head withBody:(NSMutableDictionary *)body{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:head forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    requestManage *requset = [[requestManage alloc]init];
    NSString *result = [requset post:APPIP postDataDic:dic error:nil];
    return result;
}
+(NSString*)GetCurTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];
    
    NSString*timeString=[formatter stringFromDate: [NSDate date]];
    
    return timeString;
}
+(NSString *) hmacSha1:(NSString*)key text:(NSString*)text
{
    const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [text cStringUsingEncoding:NSUTF8StringEncoding];

    uint8_t cHMAC[CC_SHA1_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    //NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:CC_SHA1_DIGEST_LENGTH];
    NSString *hash;
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", cHMAC[i]];
    hash = output;

    return hash;
}

@end
